package com.qifan.alb2b.service.timer;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import com.qifan.alb2b.dao.OrderInfoDao;
import com.qifan.alb2b.util.Constants;
import com.qifan.alb2b.util.DateUtil;

/**
 * 自动取消订单线程
 * @author hc24
 *
 */
@Component
public class AutoCancelOrder extends TimerTask {
	private static final Log logger=LogFactory.getLog(AutoCancelOrder.class);
	
	private JavaMailSender javaMailSender;
	private OrderInfoDao orderInfoDao;
	
	public void setJavaMailSender(JavaMailSender javaMailSender) {
		this.javaMailSender = javaMailSender;
	}

	public void setOrderInfoDao(OrderInfoDao orderInfoDao) {
		this.orderInfoDao = orderInfoDao;
	}

	@Override
	public void run() {
		List<Map<String, Object>> orders=orderInfoDao.queryOrder(new Date());
		for(int i=0;i<orders.size();i++){
			Map<String, Object> map=orders.get(i);
			String to=(String) map.get("EMAIL");
			if(to==null||"".equals(to.trim()))
				continue;
			String username=(String) map.get("USERNAME");
			String orderid=(String) map.get("ORDERID");
			orderInfoDao.updateStatus(orderid, Constants.ORDER_STATUS_CANCEL);//取消订单
			// 创建Helper实例并声明编码为UTF-8，true表示Multipart
			try {
				MimeMessage mime = javaMailSender.createMimeMessage();
				MimeMessageHelper helper = new MimeMessageHelper(mime, true,
						"utf-8");
				SimpleMailMessage mail=new SimpleMailMessage();
				
				mail.setFrom("jchuang@travelsky.com");
				mail.setTo(to);
				mail.setSubject("订单付款期限提醒");
				
				mail.setText(username+",您在我们网站预定的订单号为:"+orderid+"的订单已到达付款期限，该订单于 " + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")
						+ " 已自动取消，再次感谢您对我们网站的支持");
				helper.setText("<html></body><h3>订单自动取消提醒<h3><br>亲， " 
						+ ",您在我们网站预定的订单号为:"+orderid+"的订单已到达付款期限，该订单于 " + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")
						+ " 已自动取消，再次感谢您对我们网站的支持</body></html>", true);//true表示html格式
	
				javaMailSender.send(mail);// 发送
				logger.info("发送邮件："+to);
				logger.info(mail.getText());
				
			} catch (MailException e) {
				logger.error("邮件发送失败:"+e);
			} catch (MessagingException e) {
				logger.error("邮件发送失败:"+e);
			}
		}
	}

}
